package com.gis.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.gis.bean.Message;
import com.gis.util.JDBCUtils;

import cn.hutool.core.date.DateUtil;

public class MessageDao {
	QueryRunner qr = new QueryRunner(JDBCUtils.getC3p0DateSource());
	
	/**
	 * select a message by username
	 * @param username
	 * @return
	 */
	public Message selectByUsername(String username) {
		String sql = "select * from tb_message where username = ?";
		List<Message> message = new ArrayList<>();
		try {
			message = qr.execute(sql, new BeanHandler<Message>(Message.class), username);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return message.size() == 0 ? null : message.get(0);
	}
	
	/**
	 * add message
	 * @param username
	 * @param emailAddress
	 * @param randomCode
	 * @return
	 */
	public int addMessage(String username, String emailAddress, String randomCode) {
		String sql = "insert into tb_message(username, emailAddress, randomCode, sendTime) values(?,?,?,?)";
		int i = 0;
		try {
			i = qr.execute(sql, username, emailAddress, randomCode, DateUtil.now());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}
	
	/**
	 * update message
	 * @param username
	 * @param emailAddress
	 * @param randomCode
	 * @return
	 */
	public int updateMessage(String username, String emailAddress, String randomCode) {
		String sql = "update tb_message set randomCode = ?, sendTime = ? where username = ?";
		int i = 0;
		try {
			i = qr.execute(sql, randomCode,DateUtil.now(), username);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}

}
